package com.shr25.v2.common.file;

import com.shr25.v2.common.conf.V2Config;
import com.shr25.v2.util.file.FileUploadUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件处理工具类
 * @author huobing
 * @date: 2022年3月24日 下午10:33:31
 */
@Component
public class MultipartToLoaclFileUtis {
    /** v2配置 */
    private static V2Config config;
    public MultipartToLoaclFileUtis(V2Config config){
        MultipartToLoaclFileUtis.config = config;
    }

    public static List<LocalFile> toAttachmentFile(MultipartFile[] files) throws IOException {
        List<LocalFile> fileList = null;
        if(files != null &&  files.length > 0){
            fileList = new ArrayList<>();
            LocalFile attachmentFile = null;
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                if (!file.isEmpty()){
                    attachmentFile = toAttachmentFile(file);
                    fileList.add(attachmentFile);
                }
            }
        }
        return fileList;
    }

    public static LocalFile toAttachmentFile(MultipartFile file) throws IOException {
        LocalFile attachmentFile = null;
        if (!file.isEmpty()){
            attachmentFile = new LocalFile();
            attachmentFile.setFileName(file.getOriginalFilename());
            attachmentFile.setFileSize(file.getSize());
            attachmentFile.setFileSuffix(FileUploadUtils.getExtension(file));

            String avatar =  FileUploadUtils.upload(config.getProfile(), config.getUploadPath(), file);
            attachmentFile.setFileUrl(avatar);
        }
        return attachmentFile;
    }

    public static LocalFile toAttachmentFile(MultipartFile file, String uploadPath) throws IOException {
        LocalFile attachmentFile = null;
        if (file != null && !file.isEmpty()){
            attachmentFile = new LocalFile();
            attachmentFile.setFileName(file.getOriginalFilename());
            attachmentFile.setFileSize(file.getSize());
            attachmentFile.setFileSuffix(FileUploadUtils.getExtension(file));

            String avatar =  FileUploadUtils.upload(config.getProfile(), config.getUploadPath(uploadPath), file);
            attachmentFile.setFileUrl(avatar);
        }
        return attachmentFile;
    }
}
